package com.qingke.forecast;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.google.gson.Gson;
import com.qingke.forecast.model.WeatherInfo;

public class ForecastService {
	
	static String httpUrl = " http://apis.baidu.com/thinkpage/weather_api/suggestion";
	
	public static WeatherInfo forecastForCity(String city){
		String httpArg = "location="+city;
		String jsonResult = request(httpUrl, httpArg);
		jsonResult=unicodeToString(jsonResult);
		Gson gson =new Gson();
		WeatherInfo wi =gson.fromJson(jsonResult, WeatherInfo.class);
		return wi;
	}
	
	public static String request(String httpUrl, String httpArg) {
	    BufferedReader reader = null;
	    String result = null;
	    StringBuffer sbf = new StringBuffer();
	    httpUrl = httpUrl + "?" + httpArg;

	    try {
	        URL url = new URL(httpUrl);
	        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	        connection.setRequestMethod("GET");
	        
	        connection.setRequestProperty("apikey",  "4b762e3c22b64da6bc975abdfef7d287");
	        connection.connect();
			System.out.println(connection.getContentType());
	        InputStream is = connection.getInputStream();
	        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	        String strRead = null;
	        while ((strRead = reader.readLine()) != null) {
	            sbf.append(strRead);
	            sbf.append("\r\n");
	        }
	        reader.close();
	        result = sbf.toString();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return result;
	}
	public static String unicodeToString(String unicode){
		StringBuffer sb =new StringBuffer();
		int index =0;
		index=unicode.indexOf("\\u");
		while(index>=0){
			sb.append(unicode.substring(0,index));
			String hex =unicode.substring(index+2,index+6);
			sb.append((char) Integer.parseInt(hex,16));
			unicode =unicode.substring(index+6);
			index=unicode.indexOf("\\u");
		}
		sb.append(unicode);
		return sb.toString();
	}
}
